Data, Variables and
Calculations
A simple
program
Comments
A simple
program
Preprocessor directive
A simple
program
main()
A simple
program
Again comment
A simple
program
cout
A simple
program
return
Glossary
|
|
|
Preprocessor directive A command placed
within a source code listing, that directs the compiler to do something
before the rest of the source code is parsed and compiled. |
|
Comment These are put into source code
by programmers in order to better explain what the code does. When source
code is compiled into assembly language, all comments are removed. Comments
only describe code, there is no action associated with them. Since comments
are removed by the compiler, they can be written in plain English (or any
other natural language you choose!). |
|
cout In the C++ language, this is the
name given to the standard output stream. When a buffer of characters is sent
to this stream, they will appear as output on the terminal the program was
ran from. |
|
|
The main() function
|
|
|
main() declares the start of the
function, while the two curly brackets show the start and finish of the
function. Curly brackets in C are used to group statements together as in a
function, or in the body of a loop. Such a grouping is known as a compound
statement or a block. |
|
main()
ó program |
Accepting command line
arguments
|
|
|
It is possible to accept command line
arguments. |
|
|
|
int main(int argc, char* argv[]) |
|
argc
is number of command line arguments (the ARGument Count) |
|
argv[] is a listing of the command line
arguments. argv[0] is entire path to the program including its name. After
that, every element number less than argc are command line arguments. |
The main() function
Pascal C/C++
|
|
|
|
program …. |
|
… |
|
begin (* main program *) |
|
….. |
|
end. |
|
main() |
|
{
…. |
|
} |
|
OR (TRADITIONAL C): |
|
main (argc, argv) int argc; |
|
char *argv[]; |
|
{
… |
|
} |
|
OR (ANSI C): |
|
main(int argc, char * argv[]) |
|
{
…. } |
Program structure: An
example
Pascal C/C++
|
|
|
#include <iostream.h> |
|
|
|
int main() |
|
{
//print a string |
|
cout << “Hello, C++.\n”; |
|
} |
|
|
|
OR: |
|
printf(“Hello, C++.\n”); |
Lexical
Conventions
Pascal C/C++
|
|
|
Not case-sensitive; upper and lower
letters are equivalent |
|
|
|
Example: somename, Somename, SomeName,
SOMENAME are all the same |
|
Case-sensitive; upper and lower case
letters are different |
|
|
|
Example: somename, Somename, SomeName,
SOMENAME are all different |
Comments
Pascal C/C++
|
|
|
|
|
|
|
|
|
(* This is a comment*) |
|
/*This is a comment*/ |
|
|
|
C++ only |
|
|
|
// This is also a comment // A comment specified |
|
// by this way extends |
|
// only to the end of the |
|
//current line |
Constants
characters
Pascal C/C++
|
|
|
‘c’ |
|
‘This is a string’ |
|
‘c’ |
|
“This is a string” |
|
“This is a string constant \ |
|
that extends over more than\ one line.” |
|
C++ only |
|
“This is a string constant” |
|
“that extends over more than” |
|
“one line.” |
Constants
Pascal C/C++
|
|
|
const |
|
size = 100; |
|
pi = 3.14159; |
|
first = ‘A’; |
|
filename = ‘A.DAT’; |
|
#define size 100 |
|
#define pi 3.14159 |
|
#define first ‘A’ |
|
#define filename “A.DAT” |
|
ANSI C and C++ only |
|
const int size=100; |
|
const float pi=3.14159; |
|
const char first = ‘A’; |
|
const char filename[]=“A.DAT”; |
What is a variable?
|
|
|
|
A variable is a place to store a piece
of information. |
|
Just as you might store a friend's
phone number in your own memory, you can store this information in a
computer's memory. |
|
Variables are your way of accessing
your computer's memory. |
|
A computer's memory can change over
time. |
|
You are able to change the information
in a computer's memory using variable |
Declaring variable
|
|
|
|
We need to tell the computer that we're
planning to store a number in a variable before you can actually do it. This
is called declaring a variable. |
|
To declare a variable, you need to know
what kind of information it will store |
|
(i.e., will it store a number, or a
text-string, or something else) and how you plan to refer to the variable
(i.e., the variable's name). |
Rules to declare variable
|
|
|
|
C++ imposes fairly strict rules on how
you can name your variables: |
|
variable names must begin with a letter |
|
variable names are
"case-sensitive" (i.e., the variable "myNumber" is
different from the variable "MYNUMBER" which is different from the
variable "mYnUmBeR") |
|
variable names can't have spaces |
|
variable names can't have special
characters (typographic symbols, such as &, %, $, £ etc.) |
|
Variables type |
|
A variable type is a description of the
kind of information a variable will store. |
Declaration of variables
Declarations of
variables
Range of types
|
|
|
C provides a wide range of types: |
|
int An integer |
|
short An integer, possibly
of reduced range |
|
long An integer, possibly of
increased range |
|
unsigned An integer with no
negative range, the spare capacity being used to increase the positive range |
|
unsigned long Like unsigned,
possibly of increased range |
|
double A double precision
floating point number |
|
float A floating point
(real) number |
|
char A single byte of
memory, enough to hold a character |
|
|
Declarations of variables
Pascal C/C++
|
|
|
var |
|
i: integer; |
|
r: real; |
|
b: boolean; |
|
c: char; |
|
j, k, l: integer; |
|
int i; |
|
float r; |
|
int b; |
|
char c; |
|
int j, k, l; |
|
|
|
unsigned int i; |
|
unsigned char c; |
Type definitions
(typedef)
|
|
|
|
Are used to clear up complicated type
declarations such as arrays of function pointers. |
|
typedef introduces new names for types.
The general rule for its use is: |
|
Pick a name for the desired type. |
|
Write a declaration defining the name
as a variable of the desired type. |
|
Precede the declaration by typedef. |
|
EXAMPLE: make String a synonym for
char* |
|
char* String; |
|
typedef char* String; |
|
String s, t; |
Declarations of new
types: Arrays
Pascal C/C++
|
|
|
type |
|
realarray = array[0..9] of real; |
|
|
|
var |
|
a: realarray; |
|
|
|
|
|
typedef float realarray[10]; |
|
|
|
realarray a; |
Declarations of new types:
Structures
Pascal C/C++
|
|
|
type |
|
student = record |
|
id: packed array[1..10] of
char; |
|
gpa: real |
|
end; |
|
|
|
var |
|
someone: student; |
|
typedef struct |
|
{ |
|
int id; |
|
char name[11]; |
|
float gpa; |
|
} student; |
|
|
|
student someone; |
Declarations of new types:
Structures
Pascal C/C++
|
|
|
type |
|
student = record |
|
id: packed array[1..10] of
char; |
|
gpa: real |
|
end; |
|
|
|
var |
|
someone: student; |
Declarations of new types:
Structures
Pascal C/C++
|
|
|
type |
|
student = record |
|
id: packed array[1..10] of
char; |
|
gpa: real |
|
end; |
|
|
|
var |
|
someone: student; |
Declarations of new
types: Union
Pascal C/C++
|
|
|
type |
|
borrower = record |
|
case boolean of |
|
false: (EBorr: employee); |
|
true: (SBorr: student) |
|
end; |
|
var |
|
someone: borrower; |
|
typedef union |
|
{
employee EBorr; |
|
student SBorr; |
|
} borrower; |
|
borrower someone; |
Declarations of new
types: Union
Pascal C/C++
|
|
|
type |
|
borrower = record |
|
case boolean of |
|
false: (EBorr: employee); |
|
true: (SBorr: student) |
|
end; |
|
var |
|
someone: borrower; |
Declarations of new types
: Union
Pascal C/C++
|
|
|
type |
|
borrower = record |
|
case boolean of |
|
false: (EBorr: employee); |
|
true: (SBorr: student) |
|
end; |
|
var |
|
someone: borrower; |
Declarations of new
types: enum
Pascal C/C++
|
|
|
type |
|
flavortype = (chocolate, vanilla); |
|
var |
|
flavor: flavortype; |
|
OR |
|
enum flavortype {chocolate, vanilla}
flavor; |
Expressions and Operators
|
|
|
|
An operator is a function which is
applied to values to give a result. |
|
Example: +, -, / |
|
|
|
Executable Statement |
|
Assignment Statement |
|
Arithmetic operators |
|
Type conversion |
|
Comparison |
|
Logical Connectors |
|
Bitwise operators |
|
Conditional expressions |
Executable
Statements
Pascal C/C++
Executable
Statements
Pascal C/C++
Assignment operator
|
|
|
An expression is evaluated, and the
result is saved in a variable: |
|
|
|
y = (m * x) + c; |
|
|
|
|
Assignment operator
|
|
|
Just as the simple assignment operator =
returns the value that it stored, all of the assignment operators return the
value stored in the variable on the left-hand-side. |
Arithmetic operators
|
|
|
+ Addition |
|
int sum = 4 + 7; |
|
- Subtraction |
|
float difference =
18.55 - 14.21; |
|
* Multiplication |
|
float product = 5 *
3.5; |
|
/ Division |
|
int quotient = 14 / 3; |
|
% Modulo Reduction
(Remainder from integer division) |
|
int remainder = 10 % 6; |
|
|
Arithmetic operators
Shorthand
Arithmetic operators
Example
|
|
|
Shorthand operations are usually very efficient and they can be
combined with another expression. |
|
|
|
X = A * B++; is equivalent to X =
A * B; |
|
B = B+1; |
|
|
|
X = A * ++B; is equivalent to
B=B+1; |
|
X=A*B; |
|
|
|
X = --C * (A + B); is equavalent
to C = C – 1; |
|
X = C * (A + B); |
|
|
|
X = C-- * (A + B); is equavalent
to X = C * (A + B);
C = C – 1; |
Arithmetic
operators
An example
Type conversion
|
|
|
|
There is usually no trouble in
assigning a value to a variable of different type. The value will be
preserved as expected except where; |
|
The variable is too small to hold the
value. In this case it will be corrupted (this is bad). |
|
The variable is an integer type and is
being assigned a real value. The value is rounded down. This is often done
deliberately by the programmer. |
Type conversion
Casting
|
|
|
Where a function expects an argument of
one type, corruption will occur if the wrong type is supplied. It is possible
to use a technique called casting to temporarily disguise the argument as the
correct type: |
Comparison
Comparison
Example (Step 1)
Comparison
Example (Step 2)
Comparison
Example (Step 3)
Boolean Logic
Boolean logic
AND
Boolean logic
OR
Boolean logic
NOT
Expressions and Operators
Logical Connectors
|
|
|
Logical connectors are frequently used
to combine relational operators, for example |
|
|
|
x < 20 && x >= 10 |
|
|
|
if ( ! acceptable ) |
|
printf("Not Acceptable
!!\n"); |
Expressions and Operators
Logical Connectors: Example
|
|
|
0 |
|
0 (AND is evaluated before OR) |
|
1 (Parenthesis are useful) |
Use of logic
connectors
AND: &&
Use of logic
connectors
OR: ||
Use of logic
connectors
NOT: !
Logical
connectors
Some remarks
Expressions and Operators
(Cont.)
Bitwise operators
Expressions and Operators
(Cont.)
Bitwise operators
Expressions and Operators
(Cont.)
Bitwise operators
|
|
|
Use the bitwise operators to modifu the
individual bits rather than the number |
|
Both operands in a bitwise expression
must be of an integral type. |
|
&, >>, << are context
sensitive. & can also be the pointer reference operator. |
|
>> can also be the input operator
in I/O expressions. |
|
<< can also be the output
operator in I/O expressions. |
Expressions and Operators
(Cont.)
Conditional expressions
|
|
|
Conditional expression evaluates to
expr2 pr expr 3, depending whether expr1 is true (non-0) or not. |
|
|
|
Expr1 ? Expr2 : Expr3; |
|
EXAMPLE: set x to the maximum of a and
b |
|
x = a > b ? a : b; |
|
|
|
Conditional expressions can be nested
inside other expressions |
|
EXAMPLE: x = sqrt(a > 0 ? a :
-a); |
Expressions and Operators
Things to remember
|
|
|
Arithmetic expressions are simple, but
watch out for subtle type conversions. The shorthand notation may save you a
lot of typing. |
|
Comparison takes two numbers and
produces a logical result. Comparisons are usually found controlling if
statements or loops. |
|
Logical connectors allow several
comparisons to be combined into a single test. Lazy evaluation can improve
the efficiency of the program by reducing the amount of calculation required. |
|
|
Variables
|
|
|
Local |
|
Global |
|
External |
|
Static |
|
Reference |
Local and global
variables
|
|
|
|
Local variables |
|
are declared within a function and can
only be used within that function. |
|
Global variables |
|
are available to all functions. |
|
Are declared as normal, but outside any
of the program’s functions. This is usually done at the beginning of the
program file, but after preprocessor directives |
|
|
External variables
|
|
|
A variable that is declared in one
file, but is used by functions from another is called an external variable in
these functions. |
|
Declaration is proceeded by the word
extern. |
|
Global and external variables can take
any type available to local variables. The data initialisation is performed
before execution of main program |
|
|
Static variables
|
|
|
|
A static variable accessed only from
the function in which it was declared is not destroyed on exit from the
function, instead its value is preserved and becomes available again when the
function is next called. |
|
|
|
static int counter; |
Reference variables
|
|
|
The point of reference variables and
functions is that you can pass a variable as a parameter and have the
variable changed in the function. |
|
|
|
int &ref = x; |
|
This is all assuming we have a variable
called x and that it is also an integer (int). But after doing this, anything
we do to ref will effect x. |
Reference
variables
An example
|
|
|
|
#include <iostream.h> |
|
void main() { |
|
int x = 10; // create integer
variable called x |
|
int &ref = x; // make a
reference variable that refers to x |
|
cout << "x is "
<< x << " and ref is " << ref << endl; |
|
cout << "Now we change
ref to equal 25 ... " << endl; |
|
ref = 25; |
|
cout << "And now x is
" |
|
<< x |
|
<< " and ref is " |
|
<< ref |
|
<< endl; |
|
} |
Reference
variables
Rules
|
|
|
|
Reference variables must be declared as
referring to something |
|
Reference variables must be the same
type as the variable they are referring to (in this case it was int). |
|
Anything you do to a reference variable
affects what it is referring to |
Input of
variables
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
s: packed array[1..10] of char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
char s[10]; |
Input with new
line
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
s: packed array[1..10] of char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
char s[10]; |
Output of variables
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
s: packed array[1..10] of char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
char s[10]; |
Output with new
lines
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
s: packed array[1..10] of char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
char s[10]; |
Input/Output from file
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
s: packed array[1..10] of char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
char s[10]; |
Importing console I/O:
IOStreams
IOStream:
Input
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
s: packed array[1..10] of char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
char s[10]; |
IOStream: Input with
while
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
s: packed array[1..10] of char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
char s[10]; |
IOStream:
Output
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
s: packed array[1..10] of char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
char s[10]; |
IOStream: Output with
comments
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
s: packed array[1..10] of char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
char s[10]; |
IOStream: Input/Output
from file
|
|
|
C++ has two basic classes to handle
files, ifstream and ofstream. To use them, include the header file fstream.h. |
|
ifstream handles file input (reading
from files). |
|
ofstream handles file output (writing
to files). The way to declare an instance of the ifstream or ofstream class
is:
ifstream a_file; |
|
//or |
|
ifstream
a_file("filename"); |
IOStream: Input/Output
from file
Parameters
|
|
|
The default mode for opening a file
with ofstream's constructor is to create it if it does not exist, or delete
everything in it if something does exist in it. The other arguments that
specify how the file should be handled are listed below:
ios::app
Opens the file, and allows additions at the end
ios::ate Opens the file, but allows additions
anywhere
ios::trunc Deletes
everything in the file
ios::nocreate
Does not open if the file must be created
ios::noreplace Does
not open if the file already exists
EXAMPLE: |
|
ofstream
a_file("test.txt", ios::nocreate); |
IOStream: Input/Output
from file
Example
|
|
|
#include <fstream.h> |
|
#include <iostream.h> |
|
int main() { |
|
char str[10]; //Used later |
|
ofstream
a_file("example.txt"); //Creates an instance of ofstream, and
opens example.txt |
|
a_file<<"This text will
now be inside of example.txt"; //Outputs to example.txt through a_file |
|
a_file.close(); //Closes up the
file |
|
ifstream
b_file("example.txt"); //Opens for reading the file |
|
b_file>>str; //Reads one
string from the file cout<<str; //Should output ‘this' |
|
b_file.close(); |
|
} |
IOStream: Input/Output
from file
Pascal C/C++
|
|
|
var |
|
c: char; |
|
i: integer; |
|
r: real; |
|
fi, fo: char; |
|
#include <stdio.h> |
|
char c; |
|
int i; |
|
float r; |
|
FILE * fi, fo; |